package com.soilflow.info.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soilflow.common.annotation.DataScope;
import com.soilflow.common.domain.*;
import com.soilflow.common.domain.dto.LandContractDto;
import com.soilflow.common.domain.vo.LandContractVo;
import com.soilflow.common.utils.SecurityUtils;
import com.soilflow.common.utils.StringUtils;
import com.soilflow.common.utils.bean.BeanUtils;
import com.soilflow.info.service.*;
import com.soilflow.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soilflow.info.mapper.LandContractMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
@author dhp
@date 2023/5/4 - 13:15
*/
@Service
public class LandContractServiceImpl extends ServiceImpl<LandContractMapper, LandContract> implements LandContractService{
    @Autowired
    private LandFundService landFundService;
    @Autowired
    private ILandHireService landHireService;
    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private LandInfoService landInfoService;

    @Resource
    private LandAuctionService landAuctionService;

    @Resource
    private LandContractFileService landContractFileService;
    /* 查询【合同】
     *
     * @param id 【合同】主键
     * @return 【合同】
     */
    @Override
    public LandContractVo selectLandContractById(Long id) {
        LandContractVo landContractVos = this.baseMapper.selectLandContractById(id);
        //转换文件列表为字段
        QueryWrapper<LandContractFile> infoFileQuery = new QueryWrapper<>();
        //条件
        infoFileQuery.lambda().eq(LandContractFile::getContractId, landContractVos.getId());
        //根据土地id查询文件列表
        List<LandContractFile> list = landContractFileService.list(infoFileQuery);
        if (!ObjectUtils.isEmpty(list)&&list.size()>0){
            String file ="";
            //提取出链接
            List<String> files = list.stream().filter(e -> e.getId() != null).map(LandContractFile::getLink).collect(Collectors.toList());
            //把list转为逗号分割的字符串
            file = StringUtils.join(files, ",");
            landContractVos.setFile(file);
        }

        return landContractVos;
    }

    /**
     * 查询【合同】列表
     *
     * @param dto 【合同】
     * @return 【合同】集合
     */
    @Override
    @DataScope(deptAlias = "lc")
    public List<LandContractVo> selectLandContractList(LandContractDto dto) {
        List<LandContractVo> landContractVos = this.baseMapper.selectLandContractList(dto);
        return landContractVos;
    }

    /**
     * 新增【合同】
     *
     * @param dto 【合同】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertLandContract(LandContractDto dto) {
        boolean save = false;
        LandContract landContract = new LandContract();
        BeanUtils.copyProperties(dto, landContract);
        landContract.setDeptId(SecurityUtils.getDeptId());
        save = this.save(landContract);
        //合同新增完毕后
        landFundService.add(landContract);
        //当存在文件时
        if (!ObjectUtils.isEmpty( dto.getFile())){
            String[] split = dto.getFile().split(",");
            List<LandContractFile> fileList=new ArrayList<>();
            for (String s : split) {
                //文件
                LandContractFile landContractContractFile = new LandContractFile();
                landContractContractFile.setLink(s);
                landContractContractFile.setContractId(landContract.getId());
                fileList.add(landContractContractFile);
            }
            boolean b = landContractFileService.saveBatch(fileList);
        }
        // 新增完合同，同时新增租赁
        LandHire landHire = new LandHire();
        landHire.setLandId(dto.getInfoId());
        landHire.setPrice(BigDecimal.valueOf(Double.valueOf(dto.getAmount())));
        landHire.setTenant(dto.getPartybName());
        landHire.setTenantPhone(dto.getPhone());
        landHire.setStartTime(new Date());
        landHire.setEndTime(dto.getEnd2Time());
        landHire.setContractId(dto.getId());
        landHire.setDeptId(SecurityUtils.getDeptId());
        landHire.setDeptName(sysDeptService.selectDeptById(SecurityUtils.getDeptId()).getDeptName());
        landHireService.insertLandHire(landHire);
        // 用竞拍方式新增合同，同时修改竞拍状态。
        if (dto.getTradeType().equals("0")) {
            LandAuction landAuction = landAuctionService.getById(dto.getAuctionId());
            landAuction.setStatus("5");
            landAuctionService.updateById(landAuction);
        }


        return save;
    }

    /**
     * 修改【合同】
     *
     * @param dto 【合同】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateLandContract(LandContractDto dto) {
        boolean save = false;
        LandContract landContract = new LandContract();
        BeanUtils.copyProperties(dto, landContract);
        //新增合同
        save = this.updateById(landContract);
        //当存在文件时
        if (!ObjectUtils.isEmpty( dto.getFile())){
            //删除所有关于土地文件
            Boolean result = landContractFileService.deleteLandContractFileByContractId(landContract.getId());

            String[] split = dto.getFile().split(",");
            List<LandContractFile> fileList=new ArrayList<>();
            for (String s : split) {
                //文件
                LandContractFile landContractContractFile = new LandContractFile();
                landContractContractFile.setLink(s);
                landContractContractFile.setContractId(landContract.getId());
                fileList.add(landContractContractFile);
            }
            boolean b = landContractFileService.saveBatch(fileList);
        }
        return save;
    }

    /**
     * 批量删除【合同】
     *
     * @param ids 需要删除的【合同】主键集合
     * @return 结果
     */
    @Override
    public Boolean deleteLandContractByIds(List<Long> ids) {
        return this.removeByIds(ids);
    }
    /**
     * 校验合同名称是否唯一
     *
     * @param contractName 合同名称
     * @return 结果
     */
    @Override
    public List<Integer> checkContractNameUnique(String contractName) {
        return this.baseMapper.checkContractNameUnique(contractName);
    }

    @Override
    public int number() {
        return this.baseMapper.number();
    }
}
